package com.vcc.web.core.aspect;

import com.vcc.core.exception.NotFoundException;
import com.vcc.core.exception.PermissionException;
import com.vcc.data.entity.EnterpriseCertInfo;
import com.vcc.data.entity.User;
import com.vcc.service.client.vo.kyc.KycCertInfoVo;
import com.vcc.service.client.vo.kyc.KycVo;
import com.vcc.service.service.ClientParamService;
import com.vcc.service.service.EnterpriseCertInfoService;
import com.vcc.service.service.KycCertInfoService;
import com.vcc.service.service.KycSuccessCertInfoService;
import com.vcc.web.core.util.UserUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Component
@Aspect
public class VccKycAspect {

    private static final Logger logger = LoggerFactory.getLogger(VccKycAspect.class);
    @Autowired
    private KycCertInfoService kycCertInfoService;
    @Autowired
    private EnterpriseCertInfoService enterpriseCertInfoService;
    @Autowired
    private ClientParamService clientParamService;

    //controller层切点
    @Pointcut("@annotation(com.vcc.core.annotations.KycReject)")
    public void controllerAspect() {
    }

    @Before("controllerAspect()")
    public void deBefore(JoinPoint joinPoint) throws Exception {
        User user = UserUtil.get();
        if (!UserUtil.hasParent()) {
            return;
        }
        String clientUserFlag = clientParamService.getValueByCodeAndUserIdOrDefaultValue("HAS_PERSONAL", user.getId(), "true");
        if (clientUserFlag.equals("false")) {
            return;
        }
        //如果是企业认证
        boolean flag = false;
        if (kycCertInfoService.existsByUserId(user.getId())) {
            KycCertInfoVo certInfo = kycCertInfoService.getByUserId(user.getId());
            if (certInfo.getStatus() == 2) {
                throw new PermissionException("资料认证审核中无法操作");
            }
            if (certInfo.getStatus() == 1) {
                throw new PermissionException("资料认证未通过无法操作");
            }
            flag = true;
        }
        if (enterpriseCertInfoService.existsByUserId(user.getId())) {
            EnterpriseCertInfo certInfo = enterpriseCertInfoService.getByUserId(user.getId());
            if (certInfo.getStatus() == 2) {
                throw new PermissionException("企业认证审核中无法操作");
            }
            if (certInfo.getStatus() == 1) {
                throw new PermissionException("企业认证未通过无法操作");
            }
            flag = true;
        }
        if (!flag) {
            throw new NotFoundException("没有提交认证信息");
        }
    }


}
